import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getAllCategories } from '../api/category'

export interface Category {
  id: number
  name: string
  description?: string
  icon?: string
  sort?: number
  status?: string
  createdAt?: string
  updatedAt?: string
}

export const useCategoryStore = defineStore('category', () => {
  // 长期存储分类列表
  const categories = ref<Category[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  async function fetchCategories() {
    loading.value = true
    error.value = null
    try {
      const res = await getAllCategories()
      const list = Array.isArray(res) ? res : (res.data || [])
      categories.value = list.map((c: any) => ({
        id: c.id,
        name: c.name,
        description: c.description,
        icon: c.icon,
        sort: c.sort,
        status: c.status,
        createdAt: c.createdAt,
        updatedAt: c.updatedAt
      }))
    } catch (e: any) {
      error.value = e.message || '获取分类失败'
    } finally {
      loading.value = false
    }
  }

  // 自动全局加载（只加载一次）
  if (typeof window !== 'undefined' && categories.value.length === 0) {
    fetchCategories()
  }

  return { categories, loading, error, fetchCategories }
})
